/**
 *  程序员1  请大哥来助阵  
 *  问我那么多注释没删？  不敢删呀  变来变去 2 越来越看自己写的是个屎
 *                    _ooOoo_
 *                   o8888888o
 *                   88" . "88
 *                   (| -_- |)
 *                    O\ = /O
 *                ____/`---'\____
 *              .   ' \\| |// `.
 *               / \\||| : |||// \
 *             / _||||| -:- |||||- \
 *               | | \\\ - /// | |
 *             | \_| ''\---/'' | |
 *              \ .-\__ `-` ___/-. /
 *           ___`. .' /--.--\ `. . __
 *        ."" '< `.___\_<|>_/___.' >'"".
 *       | | : `- \`.;`\ _ /`;.`/ - ` : | |
 *         \ \ `-. \_ __\ /__ _/ .-` / /
 * ======`-.____`-.___\_____/___.-`____.-'======
 *                    `=---='
 *
 * .............................................
 *          佛祖保佑             永无BUG
 */
const app = getApp()
import {
  request
} from '../../utils/api'
var util = require('../../utils/WSCoordinate.js')
// 小程序地图jdk  自定义搜索地点用
var QQMapWX = require('../../assets/js/qqmap-wx-jssdk.min.js');
// 实例化API核心类
var qqmapsdk = new QQMapWX({
  key: 'MSPBZ-V5ARU-7VXVP-4MSXQ-KD2MZ-WWBMP' // 必填
})
Page({
  data: {
    // 用户定位
    latitude: '',
    longitude: '',
    // 定位城市  
    city: '',
    country: '',
    // 搜索框值
    value: '',
    statusBarHeight1: app.globalData.statusBarHeight + 45,
    // 地图标记集合
    markers: [],
    // 缩放视野索要包含的所有经纬度
    points: [],
    // 点击的标记id
    mkId: '',
    // 是否显示站点路线
    showPath: false,
    // 是否显示城市选择
    showCities: 'hidden',
    // 点击站点的路线集合
    pathList: [],
    // 点击的站点名字
    stationName: '',
    // 车辆位置数据
    carAddrData: {},
    // 缩放级别
    scale: 13,
  },
  // 定位  回到当前
  dingwei() {
    // var mapCtx = wx.createMapContext('map'); //wxml中map标签的id值
    // mapCtx.moveToLocation();
    console.log(getCurrentPages());
    app.globalData.selectAddr = null
    if (getCurrentPages().length != 0) {
      getCurrentPages()[getCurrentPages().length - 1].onLoad()
   }
  },
  // 视野发生变化时触发，
  regionchange(e) {
    let that = this
    // console.log(e)
    // 拖动地图时获取到移动地图后的中心点
    if (e.type == 'end') {
      var mapCtx1 = wx.createMapContext('map'); //wxml中map标签的id值
      mapCtx1.getCenterLocation({
        success(res) {
          console.log('中心点', res);
          that.getStation20(that.data.city, that.data.country, res.latitude, res.longitude)
        }
      });
      // 限制地图缩放级别
      // mapCtx1.getScale({
      //   success(res) {
      //     console.log('缩放级别', res);
      //   }
      // })
    }
  },
  // 点击地图时触发
  clickMap(e) {
    console.log(e);
    return
  },
  // 点击标记点时触发
  markertap(e) {
    console.log(e)
    this.setData({
      mkId: e.detail.markerId
    })
    request({
      url: '/passengerTraffic-applet/applet/indexApi/stationLine',
      method: 'POST',
      data: {
        stationId: e.detail.markerId
      } 
    }).then(res => { 
      console.log(res);
      var carDataList = []
      if (res.data) {
        res.data.lineList.filter(item => {
          // item.lineNameString = item.lineNameString.split('-')
          carDataList.push(item.vehicleMessage)
          // return item
        })
        this.setData({
          pathList: res.data.lineList,
          stationName: res.data.stationName,
          carAddrData: res.data.vehicleMessage
        })
      }
    })
    this.setData({
      showPath: true
    })
  },
  // 点击控件时触发
  controltap(e) {
    console.log(e.detail.controlId)

  },
  // 选择地点  搜索框获取焦点触发
  selectAddr() {
    wx.switchTab({
      url: '/pages/pathPlan/search/search',
    })

  },
  // 隐藏路线
  hiddenPath: function () {
    this.setData({
      showPath: false
    })
  },
  // 选择城市
  selectCity: function () {
    console.log(11);
    this.setData({
      showPath: false
    })
    app.globalData.goCityWay = 1
    wx.navigateTo({
      url: '/pages/home/cities/cities?city=' + this.data.city,
    })
  },
  // 跳转路线详情
  goDetail(e) {
    // console.log(e);
    let lineId = e.currentTarget.dataset.lineid
    let type = e.currentTarget.dataset.type
    wx.navigateTo({
      url: '/pages/home/pathDetail/pathDetail?lineId=' + lineId + '&mkId=' + this.data.mkId + '&type=' + type,
    })
  },
  // 获取中心点 附近20个站点
  getStation20(city, country, lat, long) {
    let that = this
    wx.showLoading({title: '加载中'})
    request({
      url: '/passengerTraffic-applet/applet/indexApi/countryStation',
      method: 'post',
      data: {
        city: city,
        country: country,
        centerLong: long,
        centerLat: lat
      }
    }).then(res => {
      console.log(res);
      if (res.code == 1 && res.data.length != 0) {
        wx.hideLoading()
        let mks = []
        // let points1 = []
        res.data.filter((item, index) => {
          let obj0 = util.transformFromWGSToGCJ(item.stationLatitude - 0, item.stationLongitude - 0)
          mks.push({
            callout: {
              content: item.stationName,
              padding: 5,
              borderRadius: 3,
              display: 'BYCLICK'
            },
            iconPath: "/assets/images/bus4.png",
            id: item.stationId,
            latitude: obj0.latitude,
            longitude: obj0.longitude,
            width: 20,
            height: 20
          })
          // points1.push({
          //   latitude: obj0.latitude,
          //   longitude: obj0.longitude,
          // })
        })
        that.setData({
          markers: mks,
          // points: points1
        })
      } else {
        wx.hideLoading()
        wx.showToast({
          title: '当前区域暂无站点！',
          icon: 'none',
          duration: 1500
        })
      }
    })
   
  },
  onLoad: function (options) {
    if (app.globalData.selectAddr) {
      return
    }
    console.log(666);
    let that = this
    // 获取定位
    wx.getLocation({
      success(res) {
        console.log(res);
        let obj3 = util.transformFromWGSToGCJ(res.latitude - 0, res.longitude - 0)
        that.setData({
          latitude: obj3.latitude,
          longitude: obj3.longitude
        })
        // if (app.globalData.selectAddr) {
        //   return
        // }
        request({
          url: '/passengerTraffic-applet/applet/chinaApi/getAddr',
          method: 'POST',
          data: {
            latitude: obj3.latitude,
            longitude: obj3.longitude
          }
        }).then(res1 => {
          console.log('城市', res1);
          that.setData({
            city: res1.city,
            country: res1.district
          })
          app.globalData.selectAddr = {
            city: res1.city,
            country: res1.district
          }
          // 全局保存用户的定位  位置
          app.globalData.locationAddr = {
            city: res1.city,
            country: res1.district,
            latitude: obj3.latitude,
            longitude: obj3.longitude
          }
          // 获取到定位以后  查看该区域是否有开通  如果有 显示站点
          // request({
          //   url: '/passengerTraffic-applet/applet/indexApi/countryStation',
          //   method: 'POST',
          //   data: {
          //     city: res1.city.slice(0, -1),
          //     country: res1.district
          //   }
          // }).then(res4 => {
          //   console.log(res4);
          //   if(res4.data.length != 0) {
          //     let mks = []
          //     let points1 = []
          //     res4.data.filter((item, index )=> {
          //       let obj0 = util.transformFromWGSToGCJ(item.stationLatitude - 0, item.stationLongitude - 0)
          //       mks.push({
          //         callout: {
          //           content: item.stationName,
          //           padding: 5,
          //           borderRadius: 3,
          //           display: 'BYCLICK'
          //         },
          //         iconPath: "/assets/images/bus4.png",
          //         id: item.stationId,
          //         latitude: obj0.latitude,
          //         longitude: obj0.longitude,
          //         width: 20,
          //         height: 20
          //       })
          //       points1.push({
          //         latitude: obj0.latitude,
          //         longitude: obj0.longitude,
          //       })
          //     })
          //     that.setData({
          //       markers: mks,
          //       points: points1
          //     })
          //   } else {
          //     wx.showToast({
          //       title: '当前区域暂未开通！',
          //       icon: 'none',
          //       duration: 2500
          //     })
          //   }
          // })
          that.getStation20(res1.city, res1.district, obj3.latitude, obj3.longitude)
        })
      }
    })
  },
  onShow: function () {
    let that = this
    var selectAddr = getApp().globalData.selectAddr
    var locationAddr = getApp().globalData.locationAddr
    console.log(selectAddr);
    if(selectAddr && selectAddr.country == locationAddr.country) {
      this.getStation20(locationAddr.city, locationAddr.country, locationAddr.latitude, locationAddr.longitude)
      return
    }
    if (selectAddr && selectAddr.country != locationAddr.country) {
      this.setData({
        city: selectAddr.city,
        country: selectAddr.country
      })
      request({
        url: '/passengerTraffic-applet/applet/indexApi/countryStationCenterPoint',
        method: 'post',
        data: {
          city: selectAddr.city,
          country: selectAddr.country
        }
      }).then(res => {
        if (res.code == 1) {
          this.setData({
            longitude: res.data.centerLong,
            latitude: res.data.centerLat,
          })
          this.getStation20(selectAddr.city, selectAddr.country, res.data.centerLat, res.data.centerLong)
        }
        return
      })

      // request({
      //   url: '/passengerTraffic-applet/applet/indexApi/countryStation',
      //   method: 'POST',
      //   data: selectAddr
      // }).then(res => {
      //   console.log(res);

      //   if(res.data != 0) {
      //     let str = ''
      //     let mks = []
      //     let points1 = []
      //     let zbList = []
      //     res.data.filter((item, index )=> {
      //       // str = str + item.stationLatitude + ',' + item.stationLongitude + ';'
      //       mks.push({
      //         callout: {
      //           content: item.stationName,
      //           padding: 5,
      //           borderRadius: 3,
      //           display: 'BYCLICK',
      //           borderColor: '#1f9ae4',
      //           borderWidth: 1
      //         },
      //         iconPath: "/assets/images/bus4.png",
      //         id: item.stationId,
      //         latitude: '',
      //         longitude: '',
      //         width: 20,
      //         height: 20,
      //         joinCluster: true
      //       },)
      //       points1.push({
      //         latitude: item.stationLatitude,
      //         longitude: item.stationLongitude,
      //       })
      //       let obj = util.transformFromWGSToGCJ(item.stationLatitude - 0, item.stationLongitude - 0)
      //       zbList.push(obj)
      //     })
      //     // str = str.slice(0, -1)
      //     // wx.request({
      //     //   url: 'https://apis.map.qq.com/ws/coord/v1/translate?locations='+ str +'&type=1&key=MSPBZ-V5ARU-7VXVP-4MSXQ-KD2MZ-WWBMP',
      //     //   method: 'get',
      //     //   success(res2) {
      //     //     console.log(res2)
      //     // })
      //     for (let i = 0; i < mks.length; i++) {
      //       mks[i].latitude = zbList[i].latitude
      //       mks[i].longitude = zbList[i].longitude
      //     }
      //     // 搜到的第一个站点经纬度当地图中心点   转换一下坐标系
      //     let obj2 = util.transformFromWGSToGCJ(res.data[0].stationLatitude - 0, res.data[0].stationLongitude - 0)
      //     that.setData({
      //       markers: mks,
      //       latitude: obj2.latitude,
      //       longitude: obj2.longitude,
      //       points: points1
      //     })
      //     // 点聚合
      //     let mapCtx = wx.createMapContext('map'); //wxml中map标签的id值
      //     mapCtx.initMarkerCluster({
      //       enableDefaultStyle: true,
      //       zoomOnClick: true,
      //       gridSize: 60,
      //       complete(res) {
      //         console.log('initMarkerCluster', res)
      //       }
      //     })
      //     //     mapCtx.moveToLocation({
      //     //       longitude: util.transformFromWGSToGCJ(res.data[0].stationLongitude - 0),
      //     //       latitude: util.transformFromWGSToGCJ(res.data[0].stationLatitude - 0)
      //     //     });
      //     //   }
      //     // })
      //   } else {
      //     console.log('001');
      //     wx.showToast({
      //       title: '该区域暂未开通！',
      //       icon: 'none',
      //       duration: 2500
      //     })
      //   }
      // })
    }
    // if(that.data.mkId) {
    //   request({
    //     url: '/passengerTraffic-applet/applet/indexApi/stationLine',
    //     method: 'POST',
    //     data: {
    //       stationId: that.data.mkId
    //     }
    //   }).then(res => {
    //     console.log(res);
    //     var carDataList = []
    //     if(res.data) {
    //       res.data.lineList.filter(item => {
    //         // item.lineNameString = item.lineNameString.split('-')
    //         carDataList.push(item.vehicleMessage)
    //         // return item
    //       })
    //       this.setData({
    //         pathList: res.data.lineList,
    //         stationName: res.data.stationName,
    //         carAddrData: res.data.vehicleMessage
    //       })
    //     } 

    //   })
    // }

  },
  getUserInfo: function (e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})